package com.tl.commonlibrary.tool;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.Base64;


import com.tl.commonlibrary.R;

import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressLint("SimpleDateFormat")
public class StringUtil {

    /**
     * 验证是否是正确的邮箱格式
     *
     * @param email
     * @return true表示是正确的邮箱格式, false表示不是正确邮箱格式
     */
    public static boolean isEmail(String email) {
        // 1、\\w+表示@之前至少要输入一个匹配字母或数字或下划线
        // 2、(\\w+\\.)表示域名. 因为新浪邮箱域名是sina.com.cn
        // 所以后面{1,3}表示可以出现一次或两次或者三次.
        String regular = "\\w+@(\\w+\\.){1,3}\\w+";
        Pattern pattern = Pattern.compile(regular);
        boolean flag = false;
        if (email != null) {
            Matcher matcher = pattern.matcher(email);
            flag = matcher.matches();
        }
        return flag;
    }

    /**
     * 验证是否是手机号格式 该方法还不是很严谨,只是可以简单验证
     *
     * @param mobile
     * @return true表示是正确的手机号格式, false表示不是正确的手机号格式
     */
    public static boolean isMobile(String mobile) {
//		// 当前运营商号段分配
//		// 中国移动号段 1340-1348 135 136 137 138 139 150 151 152 157 158 159 187 188
//		// 147
//		// 中国联通号段 130 131 132 155 156 185 186 145
//		// 中国电信号段 133 1349 153 180 189
//        String regExp = "^((13[0-9])|(15[^4,\\D])|(18[0,1-9])|(17[0,1-9]))\\d{8}$";
//        Pattern p = Pattern.compile(regExp);
//        Matcher m = p.matcher(mobile);
//        return m.matches();
        return true;
    }

//    public static String[] reg = new String[]{"" +
//            "color[\\s]*?:[\\s]*?[\\s]*?rgb[\\s]*?\\([\\s]*?0,[\\s]*?0,[\\s]*?0\\)",
//            "color[\\s]*?:[\\s]*?[\\s]*?rgb[\\s]*?\\([\\s]*?127,[\\s]*?127,[\\s]*?127\\)",
//            "color[\\s]*?:[\\s]*?[\\s]*?rgb[\\s]*?\\([\\s]*?89,[\\s]*?89,[\\s]*?89\\)",
//            "color[\\s]*?:[\\s]*?[\\s]*?rgb[\\s]*?\\([\\s]*?63,[\\s]*?63,[\\s]*?63\\)",
//            "color[\\s]*?:[\\s]*?[\\s]*?rgb[\\s]*?\\([\\s]*?38,[\\s]*?38,[\\s]*?38\\)",
//            "color[\\s]*?:[\\s]*?[\\s]*?rgb[\\s]*?\\([\\s]*?12,[\\s]*?12,[\\s]*?12\\)",
//            "color[\\s]*?:[\\s]*?[\\s]*?rgb[\\s]*?\\([\\s]*?29,[\\s]*?27,[\\s]*?16\\)",
//            "color[\\s]*?:[\\s]*?[\\s]*?rgb[\\s]*?\\([\\s]*?73,[\\s]*?68,[\\s]*?41\\)",
//            "color[\\s]*?:[\\s]*?[\\s]*?rgb[\\s]*?\\([\\s]*?15,[\\s]*?36,[\\s]*?62\\)",
//            "color[\\s]*?:[\\s]*?[\\s]*?rgb[\\s]*?\\([\\s]*?23,[\\s]*?54,[\\s]*?93\\)",
//    };

    public static String htmlFilterColor(Context context, String inputString) {
        System.out.println("reg inputString=" + inputString);
        String outputString = inputString;//<a(?![^<>]*?title[^<>]*?>).*?>
        Pattern spanPattern = Pattern.compile(context.getString(R.string.reg_html_span_no_background));//("<span(?![^<>]*?background-color[^<>]*?>).*?>");
        Matcher spanMatcher = spanPattern.matcher(inputString);
        String spanString = null;
        Pattern colorPattern = Pattern.compile(context.getString(R.string.reg_html_color_of_span));//("color[\\s]*?:[\\s]*?[\\s]*?rgb[\\s]*?\\([\\s]*?[\\d]{0,},[\\s]*?[\\d]{0,},[\\s]*?[\\d]{0,}\\)");
        Matcher colorMatcher = null;
        String colorString = null;
//		Pattern backgroundColorPattern = Pattern.compile("background-color:[\\s]*?rgb\\([\\d]{0,},[\\s]*?[\\d]{0,},[\\s]*?[\\d]{0,}\\);");
//		Matcher backgroundColorMatcher = null;
        Pattern specifiedPattern = null;
        Matcher specifiedMatcher = null;
        while (spanMatcher.find()) {
            spanString = spanMatcher.group();
            if (spanString != null) {
//				backgroundColorMatcher = backgroundColorPattern.matcher(spanString);
//				if(backgroundColorMatcher == null || !backgroundColorMatcher.find()){//没有文字背景底色
                colorMatcher = colorPattern.matcher(spanString);
                if (colorMatcher != null && colorMatcher.find()) {
                    colorString = colorMatcher.group();
                    String tempSpanString = null;
                    String[] array = context.getResources().getStringArray(R.array.reg_night_color);
                    for (int j = 0; j < array.length; j++) {
                        specifiedPattern = Pattern.compile(array[j]);
                        specifiedMatcher = specifiedPattern.matcher(colorString);
                        if (specifiedMatcher.find()) {
                            tempSpanString = colorMatcher.replaceAll("color: rgb(153,153, 153)");
                            outputString = outputString.replace(spanString, tempSpanString);
                            break;
                        }
                    }

//					}
                }
            }
        }
        System.out.println("reg outputString=" + outputString);

        return outputString;
    }

    /**
     * 过滤掉不符合显示�?��的字符串
     *
     * @param inputString
     * @return
     */
    public static String html2Text(String inputString) {
        String htmlStr = inputString; // 含html标签的字符串
        String textStr = "";
        Pattern p_script;
        Matcher m_script;
        Pattern p_style;
        Matcher m_style;
        Pattern p_html;
        Matcher m_html;

        Pattern p_html1;
        Matcher m_html1;

        try {
            String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>"; // 定义script的正则表达式{�?script[^>]*?>[//s//S]*?<///script>
            String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>"; // 定义style的正则表达式{�?style[^>]*?>[//s//S]*?<///style>
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
            String regEx_html1 = "<[^>]+";
            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签

            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); // 过滤style标签

            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签

            p_html1 = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);
            m_html1 = p_html1.matcher(htmlStr);
            htmlStr = m_html1.replaceAll(""); // 过滤html标签

            textStr = htmlStr;

        } catch (Exception e) {
            System.err.println("Html2Text: " + e.getMessage());
        }
        return textStr;// 返回文本字符�?
    }

    /**
     * 获取当前时间 格式为：yyyy-MM-dd_hh:mm:ss
     *
     * @param format
     * @return
     */
    public static final String getStringfromDateTime(String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String str = formatter.format(new Date());
        return str;
    }

    /**
     * splite the src with sep, and place them in a array
     *
     * @param src
     * @param sep
     * @return
     */
    public static String[] splite(String src, String sep) {
        Vector<String> v = new Vector<String>();
        int index;
        int fromIndex = 0;
        while ((index = src.indexOf(sep, fromIndex)) != -1) {
            v.addElement(src.substring(fromIndex, index));
            fromIndex = index + sep.length();
        }
        v.addElement(src.substring(fromIndex, src.length()));
        String[] result = new String[v.size()];
        for (int i = 0; i < result.length; i++) {
            result[i] = v.elementAt(i);
        }
        return result;
    }

    public static ArrayList<String> spliteList(String src, String sep) {
        if (TextUtils.isEmpty(src)) {
            return null;
        }
        Vector<String> v = new Vector<String>();
        int index;
        int fromIndex = 0;
        while ((index = src.indexOf(sep, fromIndex)) != -1) {
            v.addElement(src.substring(fromIndex, index));
            fromIndex = index + sep.length();
        }
        v.addElement(src.substring(fromIndex, src.length()));
        ArrayList<String> result = new ArrayList<String>();
        for (int i = 0, n = v.size(); i < n; i++) {
            result.add(v.elementAt(i));
        }
        result.remove(result.size() - 1);
        return result;
    }

    /**
     * splite the src with sep, place them in a array, and replace sep with
     * sep_code
     *
     * @param src
     * @param sep
     * @param sep_code
     * @return
     */
    public static String[] splite(String src, String sep, String sep_code) {
        String[] result = splite(src, sep);
        replace(result, sep_code, sep);
        return result;
    }

    /**
     * replace the child string with the newStr in the src
     *
     * @param src
     * @param oldStr
     * @param newStr
     * @return
     */
    public static String replace(String src, String oldStr, String newStr) {
        int oldSize = oldStr.length();
        int newSize = newStr.length();
        int margin = newSize - oldSize;
        int offset = 0;
        StringBuffer sb = new StringBuffer(src);
        int index;
        int fromIndex = 0;
        while ((index = src.indexOf(oldStr, fromIndex)) != -1) {
            fromIndex = index + oldSize;
            sb.delete(index + offset, fromIndex + offset);
            sb.insert(index + offset, newStr);
            offset += margin;
        }
        return sb.toString();
    }

    public static void replace(String[] src, String oldStr, String newStr) {
        for (int i = 0; i < src.length; i++) {
            src[i] = replace(src[i], oldStr, newStr);
        }
    }

    public static String toUpperZh(int numa) {
        String num = String.valueOf(numa);
        String numStr = "";
        char c[] = {'零', '一', '二', '三', '四', '五', '六', '七', '八', '九'};
        for (int count = 0; count < num.length(); count++) {
            // 转成数字
            char temp = num.charAt(count);
            switch (temp) {
                case '1':
                    numStr += c[1];
                    break;
                case '2':
                    numStr += c[2];
                    break;
                case '3':
                    numStr += c[3];
                    break;
                case '4':
                    numStr += c[4];
                    break;
                case '5':
                    numStr += c[5];
                    break;
                case '6':
                    numStr += c[6];
                    break;
                case '7':
                    numStr += c[7];
                    break;
                case '8':
                    numStr += c[8];
                    break;
                case '9':
                    numStr += c[9];
                    break;
                case '0':
                    numStr += c[0];
                    break;
                default:
                    break;
            }
        }
        return numStr;
    }


    /**
     * 判断日期格式:yyyy-mm-dd
     *
     * @param sDate
     * @return
     */
    public static boolean isValidDate(String sDate) {
        String datePattern1 = "\\d{4}-\\d{2}-\\d{2}";
        String datePattern2 = "^((\\d{2}(([02468][048])|([13579][26]))"

                + "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|"

                + "(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?"

                + "((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?("

                + "(((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?"

                + "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
        if ((sDate != null)) {
            Pattern pattern = Pattern.compile(datePattern1);
            Matcher match = pattern.matcher(sDate);
            if (match.matches()) {
                pattern = Pattern.compile(datePattern2);
                match = pattern.matcher(sDate);
                return match.matches();
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 验证金额
     *
     * @param str
     * @return
     */
    //[0-9]|(10)|[0-9]\\.[0-9]
    public static boolean isNumber(String str) {
        Pattern pattern = Pattern
                .compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后一位的数字的正则表达式
        Matcher match = pattern.matcher(str);
        if (match.matches() == false) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean isNumberMoney(String str) {
        Pattern pattern = Pattern
                .compile("^([1-9]\\d{0,4}|0{1})(\\.\\d{1,2})?$");
        Matcher match = pattern.matcher(str);
        if (match.matches() == false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 校验电话
     */
    public static boolean checkPhone(String args) {
        Pattern pattern = Pattern
                .compile("^\\d{8}$|^\\d{7}$");
        Matcher match = pattern.matcher(args);
        if (match.matches() == false) {
            return false;
        } else {
            return true;
        }
    }
    // ------------------------base64------------------

    /**
     * BASE64加密
     *
     * @param value
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(String value) {
        return Base64.encodeToString(value.getBytes(Charset.forName("UTF-8")), Base64.DEFAULT);
    }

    public static String formatMoney2(String price) {
        return new java.text.DecimalFormat("#0.00").format(Double.parseDouble(price) / (100));
    }

    public static String formatMoney3(String price) {
        return new java.text.DecimalFormat("#0").format(Double.parseDouble(price) / (100));
    }

    public static String formatMoneyd(String price) {
        return new java.text.DecimalFormat("#0.00").format(Double.parseDouble(price));
    }

    public static boolean isHaveGB2312(String str) {
        char[] chars = str.toCharArray();
        boolean isGB2312 = false;
        for (int i = 0; i < chars.length; i++) {
            byte[] bytes = ("" + chars[i]).getBytes(Charset.forName("UTF-8"));
            if (bytes.length == 2) {
                int[] ints = new int[2];
                ints[0] = bytes[0] & 0xff;
                ints[1] = bytes[1] & 0xff;
                if (ints[0] >= 0x81 && ints[0] <= 0xFE && ints[1] >= 0x40
                        && ints[1] <= 0xFE) {
                    isGB2312 = true;
                    break;
                }
            }
        }
        return isGB2312;
    }


    /**
     * 获取字符串的长度，中文占一个字符,英文数字占半个字符
     *
     * @param value 指定的字符串
     * @return 字符串的长度
     */
    public static int length(String value) {
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        // 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1
        for (int i = 0; i < value.length(); i++) {
            // 获取一个字符
            String temp = value.substring(i, i + 1);
            // 判断是否为中文字符
            if (temp.matches(chinese)) {
                // 中文字符长度为1
                valueLength += 2;
            } else {
                // 其他字符长度为0.5
                valueLength += 1;
            }
        }
        //进位取整
        return valueLength;
    }

    /*
    *  去掉指定字符串的开头和结尾的指定字符
    * @param stream 要处理的字符串
    * @param trimstr 要去掉的字符串
    * @return 处理后的字符串
    */
    public static String sideTrim(String stream, String trimstr) {
        // null或者空字符串的时候不处理
        if (stream == null || stream.length() == 0 || trimstr == null || trimstr.length() == 0) {
            return stream;
        }
        // 结束位置
        int epos = 0;
        // 正规表达式
        String regpattern = "[" + trimstr + "]*+";
        Pattern pattern = Pattern.compile(regpattern, Pattern.CASE_INSENSITIVE);

        // 去掉结尾的指定字符
        StringBuffer buffer = new StringBuffer(stream).reverse();
        Matcher matcher = pattern.matcher(buffer);
        if (matcher.lookingAt()) {
            epos = matcher.end();
            stream = new StringBuffer(buffer.substring(epos)).reverse().toString();
        }
        // 返回处理后的字符串
        return stream;
    }

    public static String toDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    /**
     * 获取小数点位数
     *
     * @param number
     * @return
     */
    public static int getFractionCount(String number) {
        if (TextUtils.isEmpty(number)) {
            return 0;
        }
        final int pos = number.indexOf('.');
        if (pos < 0) {
            return 0;
        }
        return number.length() - pos - 1;
    }
    public static int getMaxFractionCount(String[] numbers) {
        int count = 0;
        for (String str : numbers) {
            count = Math.max(count, getFractionCount(str));
        }
        return count;
    }
}
